#!/bin/bash

# 网络请求诊断脚本
# 使用方法: ./network-debug.sh <target_url>

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}错误: 请提供目标URL${NC}"
    echo "使用方法: $0 <target_url>"
    echo "示例: $0 https://api.example.com"
    exit 1
fi

TARGET_URL="$1"
DOMAIN=$(echo "$TARGET_URL" | sed -E 's|^https?://([^/]+).*|\1|')
PORT=80

# 检测是否为HTTPS
if [[ "$TARGET_URL" == https* ]]; then
    PORT=443
fi

echo -e "${BLUE}=== 网络请求诊断报告 ===${NC}"
echo -e "目标URL: ${YELLOW}$TARGET_URL${NC}"
echo -e "域名: ${YELLOW}$DOMAIN${NC}"
echo -e "端口: ${YELLOW}$PORT${NC}"
echo ""

# 1. DNS解析测试
echo -e "${GREEN}1. DNS解析测试${NC}"
echo "-------------------"
echo -n "解析时间: "
time nslookup "$DOMAIN" > /dev/null 2>&1 || echo -e "${RED}DNS解析失败${NC}"

echo -n "IP地址: "
dig +short "$DOMAIN" | head -1

echo -n "使用8.8.8.8 DNS: "
dig @8.8.8.8 +short "$DOMAIN" | head -1

echo ""

# 2. 网络连通性测试
echo -e "${GREEN}2. 网络连通性测试${NC}"
echo "----------------------"
echo "Ping测试 (5次):"
ping -c 5 "$DOMAIN" | tail -1

echo ""
echo "端口连通性测试:"
if command -v nc >/dev/null 2>&1; then
    if nc -z -w3 "$DOMAIN" "$PORT"; then
        echo -e "${GREEN}端口 $PORT 可达${NC}"
    else
        echo -e "${RED}端口 $PORT 不可达${NC}"
    fi
else
    echo -e "${YELLOW}nc命令不可用，跳过端口测试${NC}"
fi

echo ""

# 3. 路由跟踪
echo -e "${GREEN}3. 路由跟踪${NC}"
echo "-------------"
if command -v traceroute >/dev/null 2>&1; then
    traceroute -m 10 "$DOMAIN" | head -10
else
    echo -e "${YELLOW}traceroute命令不可用${NC}"
fi

echo ""

# 4. HTTP请求详细分析
echo -e "${GREEN}4. HTTP请求详细分析${NC}"
echo "---------------------"

# 创建临时格式文件
CURL_FORMAT=$(mktemp)
cat > "$CURL_FORMAT" << 'EOF'
     DNS解析时间: %{time_namelookup}s
     TCP连接时间: %{time_connect}s
     SSL握手时间: %{time_appconnect}s
    请求发送时间: %{time_pretransfer}s
  首字节响应时间: %{time_starttransfer}s
     总请求时间: %{time_total}s
         HTTP状态: %{http_code}
       响应大小: %{size_download} bytes
EOF

echo "执行10次请求测试:"
for i in {1..10}; do
    echo -e "${YELLOW}第 $i 次请求:${NC}"
    curl -w "@$CURL_FORMAT" -o /dev/null -s "$TARGET_URL" 2>/dev/null || echo -e "${RED}请求失败${NC}"
    echo ""
done

# 清理临时文件
rm -f "$CURL_FORMAT"

# 5. 系统资源检查
echo -e "${GREEN}5. 系统资源检查${NC}"
echo "------------------"
echo "内存使用:"
free -h | grep -E '^Mem|^Swap'

echo ""
echo "网络连接统计:"
if command -v ss >/dev/null 2>&1; then
    ss -s
else
    netstat -s | grep -E 'connections|requests' | head -5
fi

echo ""
echo "当前活跃连接数:"
if command -v ss >/dev/null 2>&1; then
    echo "TCP连接: $(ss -t | wc -l)"
    echo "UDP连接: $(ss -u | wc -l)"
else
    echo "TCP连接: $(netstat -tn | wc -l)"
fi

echo ""
echo -e "${BLUE}=== 诊断完成 ===${NC}"
